﻿using LxBasic;
using System.Reflection.PortableExecutable;

namespace LxCore
{
    public class FileManage : JsObject
    {
        public void ReadFile(string path)
        {
            //try
            //{
            LxLog.Info($"开始读取文件：{path}");

            if (path.EndsWith(".json"))
            {
                ReadJsonFile(path);
            }
            else if (path.EndsWith(".msh"))
            {
                ReadMshFile(path);
            }
            else
            {
                throw new Exception("无法识别的文件类型");
            }
            LxLog.Info($"读取文件完成：{path}");
            //}
            //catch (Exception ex)
            //{
            //    LxLog.Error($"读取失败：{path}；原因为：{ex.Message}");
            //}
        
        }
        public void ReadMshFile(string path)
        {
            if (string.IsNullOrEmpty(LxSim.Sim.Info.Directory))
            {
                LxSim.Sim.Info.FilePath = path;
            }
            MshFileReader reader = new MshFileReader();
            LxSim.Sim.Mesh.AddMesh(reader.ReadFile(path));
        }
        public void ReadJsonFile(string path)
        {
            LxSim.Sim.Info.FilePath = path;
            using (var stream = new StreamReader(path))
            {
                new JsonTextReader(new TextReaderOnStream(stream)).ReadObject(LxSim.Sim);
            }
            LxSim.Sim.Mesh.CheckCreate();
        }
        public override void FromJsonKV(string key, IJsonReader jsReader)
        {
            switch (key)
            {
                case "ReadFile":
                    ReadFile(jsReader.ReadString());
                    break;
            }
        }
        public void WriteJsonFile(string path = null)
        {
            if (string.IsNullOrEmpty(path))
            {                
                path = LxSim.Sim.Info.FilePath;
            }
            else
            {
                LxSim.Sim.Info.FilePath = path;
            }
            using (var stream = new StreamWriter(path))
            {
                new JsonTextWriter(new TextWriterOnStream(stream)).WriteObject(LxSim.Sim);
            }
        }

    }

}
